﻿//-----------------------------------------------------------------------
// <copyright file="ErrorHandlingFilter.cs" company="SLWY Enterprises">
// * Copyright (C) 2017 四川商旅无忧科技有限公司 版权所有。
// * version : 1.0
// * author  : qinchaoyue
// * FileName: ErrorHandlingFilter.cs
// * history : created by qinchaoyue 2017-10-24 12:38:37
// </copyright>
//-----------------------------------------------------------------------

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Slwy.MVC.Models;

namespace Slwy.Mvc.Filters
{
    using System;

    using Slwy.Context;
    using Slwy.Mvc.Logging;
    using Slwy.Utility.SlwyException;

    /// <summary>
    /// 异常拦截处理
    /// </summary>
    public class ErrorHandlingFilter : ExceptionFilterAttribute
    {
        /// <summary>
        /// 异常拦截处理
        /// </summary>
        /// <param name="context">异常</param>
        public override void OnException(ExceptionContext context)
        {
            if (context.Exception is SlwyArgumentNullException slwyException)
            {
                var slwyResult = new MSlwyResult {Code = 1, Data = slwyException.OverrideData};
                context.Result = new OkObjectResult(slwyResult);
            }
            else
            {
                MvcLog.Exception(context.Exception);
                var exception = context.Exception;
                if (SlwyContext.Current.Environment.ToUpper().IndexOf("PRODUCTION", StringComparison.Ordinal) != -1)
                {
                    context.Result = new OkObjectResult(
                        new MSlwyResult { Code = 0, Message = "系统异常，请稍后再试。", Data = "系统异常，请稍后再试。" });
                }
                else
                {
                    context.Result = new OkObjectResult(
                        new MSlwyResult { Code = 0, Message = exception.Message, Data = exception.ToString(), });
                }

                context.ExceptionHandled = true;
            }
        }
    }
}

